<template>
  <div>
    <van-nav-bar title="搜索" left-arrow @click-left="$router.back()" />
    <van-search
      v-model="value"
      show-action
      shape="round"
      autofocus
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <van-cell-group>
      <van-cell
        icon="search"
        v-for="(item, index) in showLink"
        :key="index"
        @click="
          $router.push({
            path: '/searchResult',
            query: { q: suggestionList[index] }
          })
        "
      >
        <template #title>
          <span class="custom-title" v-html="item"></span> </template
      ></van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { suggestion } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '',
      suggestionList: [],
      timeId: null
    }
  },
  methods: {
    onInput () {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (this.value == '') {
          this.suggestionList = []
          return
        }
        let res = await suggestion(this.value)
        this.suggestionList = res.data.data.options
        console.log(this.value)
      }, 500)
    },
    // 点击搜索
    onSearch () {
      console.log('搜索' + this.value)
      this.$router.push({ path: '/searchResult', query: { q: this.value } })
    }
  },
  computed: {
    showLink () {
      return this.suggestionList.map(value => {
        let res = new RegExp(this.value, 'ig')
        return value.replace(
          res,
          match => `<span style='color:red'>${match}</span>`
        )
      })
    }
  }
}
</script>

<style></style>
